package org.zattix.util;

import com.mysql.jdbc.StringUtils;
import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;

/**
 *
 * @author s.rainoldi
 */
public class Utility {

    private static final Pattern WHITESPACE = Pattern.compile("[\\s_]");
    private static final Pattern NONLATIN = Pattern.compile("[^a-zA-Z0-9-]");

    public static String replaceUrls(String string) {
        return string.replaceAll("(.*://[^<>[:space:]]+[[:alnum:]/])", "<a href=\"$1\">$1</a>");
    }

    public static String toUrl(String url) {
        url = url.replaceAll("[^\\d]", "");
        url = url.replace("__", "_");
        url = url.toLowerCase();
        return url;
    }

    public static String slug(String input) {
        input = input.replace("#", " sharp ");
        input = input.replace("&", " and ");
        String nowhitespace = WHITESPACE.matcher(Utility.trim(input)).replaceAll("-");
        String normalized = Normalizer.normalize(nowhitespace, Normalizer.Form.NFKD);
        String slug = NONLATIN.matcher(normalized).replaceAll("");
        return slug.toLowerCase(Locale.ENGLISH).replaceAll("-{2,}", "-");
    }

    public static String trim(String string) {
        if (string != null) {
            // Proper trim. Removes " ", \t, \n, \x0B, \f and \r from the start and end of the input string
            Pattern pattern = Pattern.compile("^\\s*(.*?)\\s*$", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(string);
            if (matcher.matches()) {
                return matcher.group(1);
            }
        }

        return "";
    }

    public static String htmlentities(String string) {
        string = string.replace("&", "&amp;");
        string = string.replace("\\", "&quot;");
        string = string.replace("<", "&lt;");
        string = string.replace(">", "&gt;");
        return string;
    }

    public static String toViewText(String string) {
        Utility.htmlentities(string);
        string = string.replaceAll("(?<!\\<a\\ href=\")http:\\/\\/[^ ]*", "<a href=\"$0\" target=\"_new\" rel=\"nofollow\">$0</a>");
        string = string.replace("\n", "<br />");
        string = string.replaceAll("(?s)\\{code\\}(.*?)\\{\\*code\\}", "<code class=\"prettyprint\">$1</code>");
        return string;
    }

    public static String getCookieValue(Cookie[] cookies, String cookieName) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                return (cookie.getValue());
            }
        }
        return null;
    }
}
